package org.ipccenter.balancechecker;

import org.ipccenter.balancechecker.requests.MiptRequest;
import org.ipccenter.balancechecker.requests.Service1Request;
import org.ipccenter.balancechecker.requests.ServiceRequest;
import org.ipccenter.balancechecker.services.MiptTelecom;
import org.ipccenter.balancechecker.services.Service1;
import org.ipccenter.balancechecker.services.ServiceType;
import org.ipccenter.balancechecker.xmlconf.XMLReader;
import org.ipccenter.balancechecker.task.Task;
import java.util.concurrent.*;
import java.util.ArrayList;
import java.util.List;

public class ServiceProcessor {
    private static ServiceProcessor ourInstance = new ServiceProcessor();

    public static ServiceProcessor getInstance() {
        return ourInstance;
    }

    private ServiceProcessor() {

    }

    public void runServices(List<ServiceType> list) {
        try {
            int serviceIndex = 0;
            ServiceRequest req = null;
            ExecutorService execSrv = Executors.newCachedThreadPool();
            Future<String>[]  futures = new Future[list.size()];
            for(ServiceType service: list) {
                if(service instanceof MiptTelecom) {
                    req = new MiptRequest();
                }
                if(service instanceof Service1) {
                    req = new Service1Request();
                }
                Task currentTask = new Task(service, req);
                futures[serviceIndex++] = execSrv.submit (currentTask);
            }
            for(Future<String> future: futures) {
                String result = future.get();
                System.out.println(result);
            }
            execSrv.shutdown();
        } catch (InterruptedException e1 ) {
            System.out.println("Thread was interrupted" + e1.getStackTrace());
        } catch ( ExecutionException e2) {
            System.out.println("Execution error" + e2.getStackTrace());
        }

    }

    public static void main(String[] args) {
        XMLReader reader = new XMLReader();
        List<ServiceType> list = new ArrayList<ServiceType>();
        list = reader.parseXML("configuration.xml");
        ServiceProcessor.getInstance().runServices(list);
    }
}
